package hello.java.app2;

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RequestTokenCore {
    public static TokenResponse requestTokenCore(String baseUrl, String userName, String password) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("grant_type", "password")
                .add("username", userName)
                .add("password", password)
                .build();

        Request request = new Request.Builder()
                .url(baseUrl + "/auth/api/connect/Token")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization",
                        "Basic QTMwRUQxMTEtQjg1QS00MzBBLTg5OEUtNEJBQjVFNDFDNkMzOkEzMEVEMTExLUI4NUEtNDMwQS04OThFLTRCQUI1RTQxQzZDMw==")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(response.body().string(), TokenResponse.class);
        }
    }
}
